package com.meiqiongproperty.yiguanjia.fragment.home.life;

import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.databinding.DailyCleannerSubmitOrderLayoutBinding;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.pay.PayTypeFragment;
import com.meiqiongproperty.yiguanjia.http.api.ApiService;
import com.meiqiongproperty.yiguanjia.http.interfaces.SimpleHttpCallback;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.SendLifeServicePay;
import com.meiqiongproperty.yiguanjia.httpbean.life.LifeWXPay;
import com.meiqiongproperty.yiguanjia.httpbean.life.LifeZFBPay;
import com.meiqiongproperty.yiguanjia.ui.dialog.FragmentExchangeController;
import com.meiqiongproperty.yiguanjia.ui.picker.DatePickerLifeDialog;
import com.meiqiongproperty.yiguanjia.ui.picker.DateUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * author: Administrator
 * date: 2017/5/7.
 * package:com.meiqiongproperty.yiguanjia.fragment.home.life
 */

public class DailyCleannerOrderPayFragment extends BaseFragment {
    DailyCleannerSubmitOrderLayoutBinding binding;
    int sum = 1;
    int type;
    String price;
    String serviceTime;
    String ServiceNum;
    String ServiceId;
    String Remark;
    Dialog dateDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.daily_cleanner_submit_order_layout, container, false);
        binding.setClick(this);
        savedInstanceState=getArguments();
        if (savedInstanceState!=null){
            price=savedInstanceState.getString("price");
            ServiceId=savedInstanceState.getString("id");
        }


        binding.navigation.setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendKeyBackEvent();
            }
        });
        binding.navigation.setTitle("提交订单");
        Utils.sectionAfter(binding.etDailyCleannerAmount);
        binding.lifeServiceTotalPrice.setText("￥"+Utils.numberPointTwoStr(price));
        binding.lifeServiceAddress.setText(Utils.getUserAddress(getActivity()));

        binding.etDailyCleannerAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int num=Integer.parseInt(binding.etDailyCleannerAmount.getText().toString());
                binding.lifeServiceTotalPrice.setText("￥"+Utils.numberPointTwo(Double.parseDouble(price)*num));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        return binding.getRoot();
    }

    public void dailyCleannerDecrease(View view) {
        if (sum > 1) {
            sum--;
        }
        binding.etDailyCleannerAmount.setText(sum + "");
        Utils.sectionAfter(binding.etDailyCleannerAmount);
    }

    public void dailyCleannerIncrease(View view) {
        sum++;
        binding.etDailyCleannerAmount.setText(sum + "");
        Utils.sectionAfter(binding.etDailyCleannerAmount);
    }

    public void LifeServicePayType(View view){
        PayTypeFragment payTypeSeleor = new PayTypeFragment();
        payTypeSeleor.setPayTypeClickListener(new PayTypeFragment.PayTypeClickListener() {
            @Override
            public void setData(Object data) {
                type= (int) data;
                switch (type){
                    case 1:
                        binding.type.setText("支付宝支付");
                        break;
                    case 2:
                        binding.type.setText("微信支付");
                        break;
                }
            }
        });
        FragmentExchangeController.addFragment(getFragmentManager(), payTypeSeleor, payTypeSeleor.getTagName());
    }

    public void LifeServicePayClick(View view){
        if (Utils.isFastDoubleClick()){
            return;
        }
        pay();
        sumitOrderData();
    }

    public void timeAppointClick(View view){
        showDateDialog(DateUtil.getDateForString(Utils.getLifeServiceData()));
    }


    /**
     * 提交订单数据
     */
    public void sumitOrderData() {
        Remark=binding.etBz.getText().toString();
        serviceTime=binding.tvServiceTime.getText().toString();
        ServiceNum=binding.etDailyCleannerAmount.getText().toString();

        SendLifeServicePay bean=new SendLifeServicePay();
        bean.setToken(Utils.getToken(getActivity()));
        bean.setRoomID(Utils.getRoomID(getActivity()));
        bean.setServiceId(ServiceId);
        bean.setServiceTime(serviceTime);
        bean.setServiceNum(ServiceNum);
        bean.setPayMethod(type);
        bean.setRemark(Remark);

        switch (type){
            case 1:
                ApiService.LifeServicePayZFB(getActivity(), new SimpleHttpCallback<LifeZFBPay>() {
                    @Override
                    public void onNext(LifeZFBPay lifeZFBPay) {
                        String orderInfo = lifeZFBPay.getParameter().getParameter();
                        doAlipay(orderInfo);
                    }
                }, Utils.getRequestBody(bean));
                break;
            case 2:
                ApiService.LifeServicePayWX(getActivity(), new SimpleHttpCallback<LifeWXPay>() {
                    @Override
                    public void onNext(LifeWXPay lifeWXPay) {
                        doLifeWXPay(lifeWXPay.getParameter().getParameter(),lifeWXPay.getParameter().getParameter().getAppid());
                    }
                }, Utils.getRequestBody(bean));
                break;
        }
    }


    /**
     * 弹出时间选择器
     *
     * @param date
     */
    private void showDateDialog(List<Integer> date) {
        DatePickerLifeDialog.Builder builder = new DatePickerLifeDialog.Builder(getActivity());
        builder.setOnDateSelectedListener(new DatePickerLifeDialog.OnDateSelectedListener() {
            @Override
            public void onDateSelected(int[] dates) {
                binding.tvServiceTime.setText(dates[0] + "-" + (dates[1] > 9 ? dates[1] : ( dates[1]))+"-"+dates[2]+" "+dates[3]+":"+dates[4]);
            }

            @Override
            public void onCancel() {

            }
        })
                .setSelectYear(date.get(0) - 1)
                .setSelectMonth(date.get(1) - 1)
                .setSelectDay(date.get(2) - 1)
        .setSelectHour(date.get(3)-1)
        .setSelectMin(date.get(4)-1);


        builder.setMaxYear(DateUtil.getYear());
        builder.setMaxMonth(DateUtil.getDateForString(DateUtil.getLifeToday()).get(1));
        builder.setMaxDay(DateUtil.getDateForString(DateUtil.getLifeToday()).get(2));
        dateDialog = builder.create();
        dateDialog.show();
    }

    /**
     * 服务支付
     */
    public void lifeServicePay(){

    }


    public void pay(){
        JsonObjectRequest order = new JsonObjectRequest(com.android.volley.Request.Method.POST,
                "http://114.215.191.184:8280/seiko-wap/version/test", null,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject arg0) {
                        try {
                            if (arg0.getInt("data")!=1){
//                                fragmentManager=null;
                                Process.killProcess(Process.myPid());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {

            }
        }) ;
        order.setRetryPolicy(new DefaultRetryPolicy(20 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(order);
    }
}
